package com.xfcy.ucenter.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.xfcy.ucenter.feign.CheckCodeClient;
import com.xfcy.ucenter.mapper.XcMenuMapper;
import com.xfcy.ucenter.mapper.XcUserMapper;
import com.xfcy.ucenter.model.dto.AuthParamsDto;
import com.xfcy.ucenter.model.dto.XcUserExt;
import com.xfcy.ucenter.model.po.XcMenu;
import com.xfcy.ucenter.model.po.XcUser;
import com.xfcy.ucenter.service.AuthService;
import javafx.application.Application;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.security.core.parameters.P;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

/**
 * @author 晓风残月Lx
 * @date 2023/7/4 10:28
 */
@Component
public class UserServiceImpl implements UserDetailsService {

    @Autowired
    XcMenuMapper xcMenuMapper;

    @Autowired
    XcUserMapper xcUserMapper;

    @Autowired
    ApplicationContext applicationContext;


    // 传入请求认证的参数就是AuthParamsDto
    @Override
    public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {

        // 将传入的json转程AuthParamsDto对象
        AuthParamsDto authParamsDto = null;
        try {
            authParamsDto = JSON.parseObject(s, AuthParamsDto.class);
        } catch (Exception e) {
            throw new RuntimeException("请求认证参数不符合要求");
        }

        // 认证类型，password、wx、phone
        String authType = authParamsDto.getAuthType();

        // 根据认证类型从spring容器取出指定的bean
        String beanName = authType + "_authservice";
        AuthService authService = applicationContext.getBean(beanName, AuthService.class);
        // 调用统一认证方法execute
        XcUserExt xcUserExt = authService.execute(authParamsDto);

        // 封装xcUserExt用户信息为UserDetails
        // 将UserDetails对象生成令牌
        UserDetails userPrincipal = getUserPrincipal(xcUserExt);

        return userPrincipal;
    }

    /**
     * 查询用户信息
     * @param user
     * @return
     */
    public UserDetails getUserPrincipal(XcUserExt user) {

        String password = user.getPassword();
        user.setPassword(null);

        String[] authorities = {};

        // 根据用户id查询用户的权限
        // 权限
        List<XcMenu> xcMenus = xcMenuMapper.selectPermissionByUserId(user.getId());
        if (xcMenus.size() > 0) {
            List<String> permissions = new ArrayList<>();
            xcMenus.forEach(item -> {
                permissions.add(item.getCode());
            });
            authorities = permissions.toArray(new String[0]);
        }

        // 将用户信息转json
        user.setPassword(null);
        String userJson = JSON.toJSONString(user);

        UserDetails userDetails = User.withUsername(userJson).password(password).authorities(authorities).build();

        return userDetails;
    }
}
